import requests
import json
import os
import base64
import csv


class GetResume(object):

    def __init__(self):
        self.user_id = '3b1c22f0-57f0-11ec-901b-5fbd330b1c43'
        self.secret_key = '0383ec64-aa52-4441-823a-fae4f10a457d'
        self.headers = {
                        'id': self.user_id,  # 替换ID
                        'secret': self.secret_key  # 替换密匙
                    }
        self.url = 'https://api.xiaoxizn.com/v1/parser/parse_base'

    def get_data(self, request_json):
        """
        获取xiaoxin返回的简历信息
        :param filename:
        :param bs64_content:
        :return:
        """
        result = requests.post(self.url, json=request_json, timeout=15, verify=False, headers=self.headers)
        return result

    def turn_bs64(self, file):
        """
        转bs64
        :param file:
        :return:
        """
        return base64.b64encode(file)

    def get_filename_content(self, path):
        """
        获取filename、文件内容
        :param path:
        :return: file_content, filename
        """
        file_list = os.listdir(path)
        print(file_list)
        for file in file_list:
            with open(path + file, "rb") as f:
                yield f.read(), file

    def get_info(self, json_data):
        """
        获取解析出来的数据
        :param data:
        :return:
        """
        with open("./dats.txt", "a+") as f:
            f.write(json_data + '\n')
        data = json.loads(json_data)
        contact_info = data.get("parsing_result").get('contact_info')
        basic_info = data.get("parsing_result").get("basic_info")
        if not contact_info or not basic_info:
            return
        # print(contact_info["phone_number"], contact_info["email"], contact_info['wechat'])
        # print(basic_info.get("name"), basic_info.get("gender"), basic_info.get("work_start_year"),
        # basic_info.get("current_location"))
        # print(basic_info.get("age"), basic_info.get("num_work_experience"), basic_info.get("school_name"),
        # basic_info.get('school_type'))
        # print(basic_info.get("degree"), basic_info.get("major"), basic_info.get("industry"))
        with open("./resume.csv", 'a', encoding="utf8") as f:
            row = [
                basic_info.get("name"), contact_info.get("phone_number"), contact_info.get("email"),
                basic_info.get("num_work_experience"), basic_info.get("gender"), basic_info.get("current_location"),
                basic_info.get("school_name"), contact_info.get('wechat'), basic_info.get("major"),
                basic_info.get("degree"), basic_info.get("industry"), basic_info.get("work_start_year")
            ]
            writer = csv.writer(f)
            writer.writerow(row)
            print(f"{basic_info.get('name')} 写入完毕")

    def single_write(self, content, filename):
        """
        将简历内容解析成一个字典,字典的键与Resume表的属性一一对应
        content: word简历文档二进制内容
        filename: 文件名字
        return: resume_dict 字典数据,key与Resume字段表一一对应
        """
        content = self.turn_bs64(content)
        request_json = {
            "resume_base": content.decode("utf-8"),
            "file_name": filename
        }
        # result = requests.post(self.url, json=request_json, timeout=15, verify=False, headers=self.headers)
        result = self.get_data(request_json)
        data = result.json()
        print(data)
        parsing_result = data.get('parsing_result')
        if not parsing_result:
            parsing_result = data.get('english_parsing_result')
        basic_info = parsing_result.get('basic_info')
        contact_info = parsing_result.get('contact_info')
        work_experience = parsing_result.get('work_experience')
        work_list = []
        work_dic_list = []
        if work_experience:
            for work in work_experience:
                if work.get('company_name'):
                    company_name = work.get('company_name').replace('\n', '')
                    start_time = work.get('start_time_year').replace('\n', '') + '-' + work.get('start_time_month').replace('\n', '')
                    end_time = work.get('end_time_year').replace('\n', '') + '-' + work.get('end_time_month').replace('\n', '')
                    work_list.append('公司:' + company_name + ',开始时间:' + start_time + ',结束时间:' + end_time + ',\n')
                    work_dic_list.append({'name': company_name, 'start_time': start_time, 'end_time': end_time})
        project_experience = parsing_result.get('project_experience')
        pro_lsit = []
        pro_dic_list = []
        if project_experience:
            for project in project_experience:
                pro_lsit.append('项目名:' + project.get('project_name').replace('\n', '') + ',项目简介:' + project.get('description').replace('\n', '') + ',\n')
                pro_dic_list.append({'project_name': project.get('project_name').replace('\n', ''), 'project_brief': project.get('description').replace('\n', '')})
        others = parsing_result.get('others')
        resume_dict = {
            'apply_position': data.get('applied_job') if data.get('applied_job') else basic_info.get('desired_position'),
            'username': basic_info.get('name', '不详'),
            'city': basic_info.get('current_location', '不详'),
            'phone': contact_info.get('phone_number', '不详'),
            'email': contact_info.get('email', '不详'),
            'gender': basic_info.get('gender', '不详'),
            'bachelor_school': basic_info.get('school_name', '不详'),
            'major': basic_info.get('major', '不详'),
            'degree': basic_info.get('degree', '不详'),
            'candidate_introduction': others.get('self_evaluation', '').replace('\n', '') if others else '',
            'work_experience': ''.join(work_list),
            'project_experience': ''.join(pro_lsit),
            'born_address': basic_info.get('birthplace', '不详'),
            'age': basic_info.get('age') if basic_info.get('age') else '不详',
        }
        # self.get_info(result.text)
        return resume_dict, work_dic_list, pro_dic_list

    def run(self, path):
        """
        run
        :param path:
        :return:
        """
        count = 0
        for content, filename in self.get_filename_content(path):
            content = self.turn_bs64(content)
            request_json = {
                "resume_base": content.decode("utf-8"),
                "file_name": filename
            }
            # result = requests.post(self.url, json=request_json, timeout=15, verify=False, headers=self.headers)
            result = self.get_data(request_json)
            print(result.text)
            self.get_info(result.text)
            # if count == 1:
            #     return result.text
            count += 1


if __name__ == '__main__':
    GR = GetResume()
    GR.run("./BASIS/")

